import axios from 'axios';
import router from '@/router'
import { Message } from "view-design";


// https://www.cnblogs.com/chaoyuehedy/p/9931146.html

axios.defaults.timeout = 10000; //1s超时
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.interceptors.request.use(
    config => {
        let token = localStorage.getItem("token")
        let username = localStorage.getItem("username")
        // console.log("拦截设置token")
        if(token){
            config.headers['token'] = token
            config.headers['username'] = username
        }
        return config
    },
    error => {
        return Promise.reject(error);
    }
);
// response => {   
//     // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据     
//     // 否则的话抛出错误
//     if (response.status === 200) {            
//         return Promise.resolve(response);        
//     } else {            
//         return Promise.reject(response);        
//     }    
// },   

axios.interceptors.response.use(
    response => {
        // console.log("拦截200响应")
        return response;
    },
    error => {
        if (error.response){
            console.log("拦截error响应")
            switch (error.response.status){
                case 400:
                    Message.error('无效token,token被篡改');
                    // 清除token
                    localStorage.removeItem('token');
                    setTimeout(() => {                        
                        router.replace({                            
                            path: '/login',                            
                            query: { 
                                redirect: router.currentRoute.fullPath 
                            }                        
                        });                    
                    }, 200);                    
                    break; 
                case 401:
                    Message.error('token过期或未登录，请重新登录');
                    localStorage.removeItem("token")
                    setTimeout(() => {                        
                        router.replace({                            
                            path: '/login',                            
                            query: { 
                                redirect: router.currentRoute.fullPath 
                            }                        
                        });                    
                    }, 200);    
                    break;
                case 404:
                    Message.error('网络请求不存在');
                    break;
                case 500:
                    Message.error('请求出错，状态码500');
                    break;
                case 666:
                    Message.error('服务器连不上');
                    break;
                case 4001:{
                    let err='访问k8s接口必须携带cluster_name header,请先配置k8s集群，检查header'
                    Message.error(err)
                    alert(err);
                    break    
                }
                case 5000:{
                    let tip='请先在集群管理=>集群信息=>创建集群下配置k8s集群'
                    Message.error(tip)
                    alert(tip);
                    break
                }

                default:
                    Message.error(error.response.data)
            }
        }
        // 返回接口返回的错误信息
        return Promise.reject(error);
    }
);

export function post(url,data,headers,timeout,params) {
    timeout = timeout || 15000
    params = params || {}
    return new Promise((resolve,reject) => {
        axios({
            method:'post',
            url:url,
            data:data,
            headers:headers,
            timeout: timeout,
            params:params,
        }).then(response =>{
            resolve(response);
        }).catch(error => {
            let err = 'post超时或者网络请求出错，请查看日志'+error
            console.log(err)
            Message.error(err)
            reject(error)
        })
    })
}

// 外部不需要再传集群名字,序列化数据
export function k8s_cluster_post(url,data,headers,timeout) {
    let cluster = localStorage.getItem('currentCluster')
    headers = headers || {}
    timeout = timeout || 30000
    headers["cluster_name"] =  cluster 
    return new Promise((resolve,reject) => {
        axios({
            method:'post',
            url:url,
            data:JSON.stringify(data),
            headers:headers,
            timeout: timeout
        }).then(response =>{
            resolve(response);
        }).catch(error => {
            let err = 'k8s请求超时或者网络请求出错:'+error
            console.log(err)
            Message.error(err)
            reject(error)
        })
    })

}

// 外部不需要再传集群，命名空间,序列化数据
export function k8s_namespace_post(url,data,headers,timeout,params) {
    data = data || {}
    headers = headers || {}
    timeout = timeout || 30000
    params = params || {}
    let cluster = localStorage.getItem('currentCluster')
    let namespace = localStorage.getItem('currentNameSpace')
    headers["cluster_name"] =  cluster 
    data["namespace"] = namespace

    return new Promise((resolve,reject) => {
        axios({
            method:'post',
            url:url,
            data:JSON.stringify(data),
            headers:headers,
            timeout: timeout,
            params:params,
        }).then(response =>{
            resolve(response);
        }).catch(error => {
            let err = 'k8s请求超时或者网络请求出错:'+error
            console.log(err)
            Message.error(err)
            reject(error)
        })
    })
}



// 外部不需要再传集群名字,序列化数据
export function es_cluster_post(url,data,headers,timeout) {
    let cluster = localStorage.getItem('currentEsCluster')
    headers = headers || {}
    timeout = timeout || 30000
    headers["cluster_name"] =  cluster 
    return new Promise((resolve,reject) => {
        axios({
            method:'post',
            url:url,
            data:JSON.stringify(data),
            headers:headers,
            timeout: timeout
        }).then(response =>{
            resolve(response);
        }).catch(error => {
            let err = 'es请求超时或者网络请求出错:'+error
            console.log(err)
            Message.error(err)
            reject(error)
        })
    })

}